package com.baizhi.hospital.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MyFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpSession session =( (HttpServletRequest)servletRequest).getSession();
		Object user = session.getAttribute("user");
		if(user != null){
			filterChain.doFilter(servletRequest,servletResponse);
		}else if(((HttpServletRequest) servletRequest).getRequestURI().contains("login") || ((HttpServletRequest) servletRequest).getRequestURI().contains("createCode")){
			filterChain.doFilter(servletRequest,servletResponse);
		}else{
			String contextPath = ((HttpServletRequest) servletRequest).getContextPath();
//			((HttpServletRequest)servletRequest).getRequestDispatcher(contextPath+"/login").forward(servletRequest,servletResponse);

			((HttpServletResponse)servletResponse).sendRedirect(contextPath+"/login.jsp");
		}
	}
}
